<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="灌溉第次" prop="periodNum">
        <el-input
          v-model="queryParams.periodNum"
          placeholder="请输入灌溉第次"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="起始日期" prop="beginDate">
        <el-date-picker clearable
          v-model="queryParams.beginDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择起始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="灌溉水量" prop="periodVol">
        <el-input
          v-model="queryParams.periodVol"
          placeholder="请输入灌溉水量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="备注" prop="periodMark">
        <el-input
          v-model="queryParams.periodMark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['distribute:WiPeriodY:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['distribute:WiPeriodY:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['distribute:WiPeriodY:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['distribute:WiPeriodY:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="WiPeriodYList" @selection-change="handleSelectionChange" :span-method="objectSpanMethod">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="种植年度" align="center" prop="cropYr" />
      <!-- <el-table-column label="种植代码" align="center" prop="plantCd" /> -->
      <el-table-column label="作物名称" align="center" prop="cropNm">
      </el-table-column>
      <el-table-column label="灌溉第次" align="center" prop="periodNum">
      </el-table-column>
      <el-table-column label="起始日期" align="center" prop="beginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="灌溉水量" align="center" prop="periodVol">
      </el-table-column>
      <el-table-column label="备注" align="center" prop="periodMark">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['distribute:WiPeriodY:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['distribute:WiPeriodY:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改年度作物灌溉周期对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="灌溉第次" prop="periodNum">
          <el-input v-model="form.periodNum" placeholder="请输入灌溉第次" />
        </el-form-item>
        <el-form-item label="起始日期" prop="beginDate">
          <el-date-picker clearable
            v-model="form.beginDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="灌溉水量" prop="periodVol">
          <el-input v-model="form.periodVol" placeholder="请输入灌溉水量" />
        </el-form-item>
        <el-form-item label="备注" prop="periodMark">
          <el-input v-model="form.periodMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
    <!-- 添加或修改灌溉制度对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-row>
              <el-col :span="12">
                  <div class="gl_bj_form_left">
                      <el-form-item label="年度" prop="cropYr">
                          <el-date-picker
                            v-model="form.cropYr"
                            type="year"
                            format="yyyy"
                            value-format="yyyy"
                            @change="getWiCropBList"
                            placeholder="选择种植年度">
                          </el-date-picker>
                      </el-form-item>
                  </div>
              </el-col>
              <el-col :span="12">
                  <div class="gl_bj_form">
                      <el-form-item label="作物名称" prop="cropCd">
                          <el-select v-model="form.cropCd">
                              <el-option
                                  v-for="item in distCropList"
                                  :key="item.cropCd"
                                  :label="item.cropNm"
                                  :value="item.cropCd"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </div>
              </el-col>
          </el-row>
          

          <div class="dm-alert">如果选择了年度、作物种类，请在灌溉定额管理下添加净灌溉定额</div>

          <div class="dm-middle-div">
              <div class="dm-middle-line"></div>
              <div class="dm-add-title">添加灌水周期</div>
              <div class="dm-add-button">
                  <el-button
                      type="primary"
                      plain
                      icon="el-icon-circle-plus-outline"
                      size="small"
                      @click="addItem"
                  >新增</el-button>
              </div>
          </div>
          <div style="position:relative" v-if="false">
            <el-input v-model="form.id" v-if="false"/>
            <el-row>
              <el-col :span="12">
                  <div class="gl_bj_form_left">
                    <el-form-item label="灌水时间(始)" prop="beginDate">
                      <el-date-picker clearable size="small"
                        v-model="form.beginDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择灌水开始时间" @change="calRange">
                      </el-date-picker>
                    </el-form-item>
                  </div>
              </el-col>
              <el-col :span="12">
                  <div class="gl_bj_form">
                    <el-form-item label="灌水时间(终)" prop="endDate">
                      <el-date-picker clearable size="small"
                        v-model="form.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择灌水结束时间" @change="calRange">
                      </el-date-picker>
                    </el-form-item>
                  </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                  <div class="gl_bj_form_left">
                    <el-form-item label="灌水天数" prop="days">
                      <el-input v-model="form.days" placeholder="请输入灌水天数" style="width:220px;" readonly="readonly" />
                    </el-form-item>
                  </div>
              </el-col>
              <el-col :span="12">
                  <div class="gl_bj_form">
                      <el-form-item label="灌水定额" prop="periodVol">
                          <el-input v-model="form.periodVol" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入灌水定额" style="width:220px;" />
                      </el-form-item>
                  </div>
              </el-col>
            </el-row>

            <div style="position: absolute;right: 10px;top: 35px;">
              <img
                v-hasPermi="['waterDistribution:wrDistYearSys:remove']"
                @click="deleteWrDistYearSys" 
                style="cursor: pointer; margin-top: 6px" 
                src="../../../assets/icons/deleteimg.png"/>
            </div>
          </div>
          <div style="position:relative" v-for="(item, index) in form.dynamicItem" :key="index">
              <div class="dm-middle-line-full" v-if="index != 0"></div>
              <el-input v-model="item.id" v-if="false"/>
              <el-row>
                  <el-col :span="12">
                      <div class="gl_bj_form_left">
                          <el-form-item 
                          label="灌水时间(始)" 
                          :prop="'dynamicItem.' + index + '.beginDate'" 
                          :rules="{ required: true, message: '灌水时间(始)不能为空', trigger: 'blur' }">
                              <el-date-picker clearable size="small"
                                v-model="item.beginDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择灌水开始时间" @change="calDynamicRange(index)">
                              </el-date-picker>
                          </el-form-item>
                      </div>
                  </el-col>
                  <el-col :span="12">
                      <div class="gl_bj_form">
                          <el-form-item 
                           label="灌水时间(终)"
                          :prop="'dynamicItem.' + index + '.endDate'"
                          :rules="{ required: true, message: '灌水时间(终)不能为空', trigger: 'blur' }">
                              <el-date-picker clearable size="small"
                                  v-model="item.endDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择灌水结束时间" @change="calDynamicRange(index)">
                              </el-date-picker>
                          </el-form-item>
                      </div>
                  </el-col>
              </el-row>
              <el-row>
                  <el-col :span="12">
                      <div class="gl_bj_form_left">
                          <el-form-item label="灌水天数" :prop="'dynamicItem.' + index + '.days'">
                              <el-input v-model="item.days" placeholder="请输入灌水天数" style="width:220px;" />
                          </el-form-item>
                      </div>
                  </el-col>
                  <el-col :span="12">
                      <div class="gl_bj_form">
                          <el-form-item 
                          label="灌水定额" 
                          :prop="'dynamicItem.' + index + '.periodVol'" 
                          :rules="{ required: true, message: '灌水定额不能为空', trigger: 'blur' }">
                              <el-input v-model="item.periodVol" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入灌水定额" style="width:220px;" />
                          </el-form-item>
                      </div>
                  </el-col>
              </el-row>
              
              <div style="position: absolute;right: 10px;top: 55px;">
                <img
                  v-hasPermi="['waterDistribution:wrDistYearSys:remove']"
                  @click="deleteItem(item, index)" 
                  style="cursor: pointer; margin-top: 6px" 
                  src="../../../assets/icons/deleteimg.png"/>
              </div>
          </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWiPeriodY, getWiPeriodY, delWiPeriodY, addWiPeriodY, updateWiPeriodY } from "@/api/waterDistribution/WiPeriodY";
import { listWiCropY } from "@/api/waterDistribution/WiCropY";

export default {
  name: "WiPeriodY",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 年度作物灌溉周期表格数据
      WiPeriodYList: [],
      // 作物类型
      distCropList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        periodNum: null,
        beginDate: null,
        endDate: null,
        periodVol: null,
        periodMark: null
      },
      // 表单参数
      form: {
        dynamicItem: [
          {
            beginDate: "",
            endDate: "",
            days: null,
            periodVol: null
          }
        ]
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
     /** 获取年度作物分类 */
    getWiCropBList() {
      listWiCropY({cropYr:this.form.cropYr}).then(response => {
        this.distCropList = response.rows;
      });
    },
    /** 查询年度作物灌溉周期列表 */
    getList() {
      this.loading = true;
      listWiPeriodY(this.queryParams).then(response => {
        this.WiPeriodYList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.getRowSpan(response.rows);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cropYr: null,
        plantCd: null,
        periodNum: null,
        beginDate: null,
        endDate: null,
        periodVol: null,
        periodMark: null,
        dynamicItem: [
           {
            beginDate: "",
            endDate: "",
            days: null,
            periodVol: null
          }
        ]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cropYr)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 添加灌水制度内容
    addItem() {
      console.log(this.form)
      this.form.dynamicItem.push({
        beginDate: "",
        endDate: "",
        days: null,
        periodVol: null
      });
    },
    deleteItem(item, index) {
      this.form.dynamicItem.splice(index, 1);
    },
    // 删除第一个灌水制度内容
    deleteWrDistYearSys() {
      this.form.beginDate = null;
      this.form.endDate = null;
      this.form.days = null;
      this.form.periodVol = null;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加年度作物灌溉周期";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cropYr = row.cropYr || this.ids
      const plantCd = row.plantCd 
      this.form.cropYr = row.cropYr
      this.getWiCropBList()
      getWiPeriodY(cropYr,plantCd).then(response => {
        let res = {
          ...response.data,
          cropCd:'',
        }
        let arr = res.dynamicItem.map((item) => {
          var beginDate = item.beginDate;
          var endDate = item.endDate;
          let days = ''
          if (null != beginDate && null != endDate && "" != beginDate && "" != endDate) {
            var start_date = new Date(beginDate);
            var end_date = new Date(endDate);
            days = (end_date - start_date)/86400000;
          }
          return {
            ...item,
            days:days,
          }
        })
        setTimeout(() => {
            res.cropCd =  this.distCropList.filter(item => item.plantCd ==  response.data.plantCd)[0].cropCd
        },200)
        res.dynamicItem = arr
        this.form = res;
        this.open = true;
        this.title = "修改年度作物灌溉周期";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cropYr != null && this.form.plantCd != null) {
            updateWiPeriodY(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWiPeriodY(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cropYrs = row.cropYr || this.ids;
      this.$modal.confirm('是否确认删除年度作物灌溉周期编号为"' + cropYrs + '"的数据项？').then(function() {
        return delWiPeriodY(cropYrs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('distribute/WiPeriodY/export', {
        ...this.queryParams
      }, `灌溉周期_${new Date().getTime()}.xlsx`)
    },
    // 计算天数
    calRange() {
      // el-date-picker本身有回显问题，按照网上建议直接用this.$set操作
      var beginDate = this.form.beginDate;
      var endDate = this.form.endDate;
      if (null != beginDate && null != endDate) {
        var start_date = new Date(beginDate);
        var end_date = new Date(endDate);
        var days = (end_date - start_date)/86400000 + 1;
        this.$set(this.form, "days", days);
      }else {
        this.$set(this.form, "days", null);
      }
    },
    // 计算动态item的天数
    calDynamicRange(index) {
      // el-date-picker本身有回显问题，按照网上建议直接用this.$set操作
      var beginDate = this.form.dynamicItem[index].beginDate;
      var endDate = this.form.dynamicItem[index].endDate;
      if (null != beginDate && null != endDate && "" != beginDate && "" != endDate) {
        var start_date = new Date(beginDate);
        var end_date = new Date(endDate);
        var days = (end_date - start_date)/86400000;
        this.$set(this.form.dynamicItem[index], "days", days);
      }else {
        this.$set(this.form.dynamicItem[index], "days", "");
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log(row,column,rowIndex,columnIndex)
      if (columnIndex === 0) {
        const _row = this.rowSpanArrYear[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row, //行
          colspan: _col //列
        };
      }
      if (columnIndex === 1) {
        const _row1 = this.rowSpanArrcropNm[rowIndex];
        const _col1 = _row1 > 0 ? 1 : 0;
        return {
          rowspan: _row1, //行
          colspan: _col1 //列
        };
      }
    },
    // 获取合并的数组
    getRowSpan(data) {
      this.rowSpanArrYear = [];
      this.rowSpanArrcropNm = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.rowSpanArrYear.push(1);
          this.rowSpanArrcropNm.push(1);
          this.positionYear = 0;
          this.positioncropNm = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          // 年
          if (data[i].cropYr === data[i - 1].cropYr) {
            this.rowSpanArrYear[this.positionYear] += 1;
            this.rowSpanArrYear.push(0);
          } else {
            this.rowSpanArrYear.push(1);
            this.positionYear = i;
          }
          // 作物名称
          if (data[i].cropNm.trim() === data[i - 1].cropNm.trim()) {
            this.rowSpanArrcropNm[this.positioncropNm] += 1;
            this.rowSpanArrcropNm.push(0);
          } else {
            this.rowSpanArrcropNm.push(1);
            this.positioncropNm = i;
          }
         
        }
      }
    },
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .dm-alert {
        font-size: 14px;
        color: red;
        padding-bottom: 5px;
        padding-left: 100px;
        // padding-bottom: 25px;
    }

    .dm-middle-div {
        width: 100%;
        height: 50px;
        // padding-bottom: 20px;
    }

    .dm-middle-line {
        background: #bee4fd;
        height: 1px;
        position: relative;
        top: 20px;
        padding-left: 100px;
        padding-right: 50px;
    }

    .dm-add-title {
        position: relative;
        left: 5px;
        font-size: 16px;
        color: #1890ff;
        font-weight: 700;
        padding-top: 8px;
        width:100px;
        background: #FFF;
    }

    .dm-add-button {
        position: relative;
        left: 690px;
        top: -25px;
    }

    .dm-middle-line-full {
        background: #bee4fd;
        height: 1px;
        padding-left: 100px;
        padding-right: 50px;
        margin-bottom: 20px;
    }
</style>
